package mashibing.class4;

import util.MathUtil;

import java.util.Arrays;

/**
 * 在一个数组中，
 * 对于每个数num，求有多少个后面的数 * 2 依然<num，求总个数
 * 比如：[3,1,7,0,2]
 * 3的后面有：1，0
 * 1的后面有：0
 * 7的后面有：0，2
 * 0的后面没有
 * 2的后面没有
 * 所以总共有5个
 *
 * @author yujiafan
 * @version 1.0.0
 * @create 2023-03-21
 */
public class Class4_4_BiggerThenRightTwice {

    public static int biggerThenRightTwiceNum(int[] arr) {
        if (arr == null || arr.length < 2) {
            return 0;
        }
        return process(arr, 0, arr.length - 1);
    }

    private static int process(int[] arr, int L, int R) {
        if (L == R) {
            return 0;
        }
        int M = L + ((R - L) >> 1);
        return process(arr, L, M)
                + process(arr, M + 1, R)
                + merge(arr, L, M, R);
    }

    private static int merge(int[] arr, int L, int M, int R) {
        // [L....M] [M+1....R]
        int ans = 0;
        int windowR = M + 1;
        // 目前囊括进来的数，是从[M+1, windowR)
        for (int i = L; i <= M; i++) {
            while (windowR <= R && arr[i] > arr[windowR] * 2) {
                windowR++;
            }
            ans += windowR - M - 1;
        }

        int[] help = new int[R - L + 1];
        int p1 = L;
        int p2 = M + 1;
        int index = 0;
        while (p1 <= M && p2 <= R) {
            help[index++] = arr[p1] <= arr[p2] ? arr[p1++] : arr[p2++];
        }
        while (p1 <= M) {
            help[index++] = arr[p1++];
        }
        while (p2 <= R) {
            help[index++] = arr[p2++];
        }
        for (int i = 0; i < help.length; i++) {
            arr[L + i] = help[i];
        }
        return ans;
    }

    public static int test(int[] arr) {
        if (arr == null || arr.length < 2) {
            return 0;
        }
        int ans = 0;
        for (int i = 0; i < arr.length - 1; i++) {
            for (int j = i + 1; j < arr.length; j++) {
                ans += arr[i] > arr[j] * 2 ? 1 : 0;
            }
        }
        return ans;
    }

    public static void main(String[] args) {
//        int[] arr = {3, 1, 7, 0, 2};
//        System.out.println(biggerThenRightTwiceNum(arr));

        int testCount = 50000;
        boolean flag = true;
        for (int i = 0; i < testCount; i++) {
            int[] arr1 = MathUtil.generateArray(100,100);
            int[] arr2 = MathUtil.copyArray(arr1);
            int ans1 = biggerThenRightTwiceNum(arr1);
            int ans2 = test(arr2);
            if(ans1 != ans2){
                flag = false;
                System.out.println("error");
                System.out.println(Arrays.toString(arr1));
            }
        }
        if(flag){
            System.out.println("success");
        }
    }
}
